//
//  DBParserRuleOptional.m
//  parser
//
//  Created by Daniel Braun on 26/05/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "DBParserRuleOptional.h"
#import "DBParser.h"
#import "DBLexer.h"

@implementation DBParserRuleOptional
+ (id) optional: (DBParserRule*)r1, ...
{
	va_list ap;
	id rul=[[[[self class]alloc]initWithAction:(SEL)0]autorelease];
	if (!rul) return nil;
	[rul appendSeq:[r1 instantiateRule]];
	va_start(ap, r1);
	for (;;) {
		DBParserRule *r;
		r=va_arg(ap, DBParserRule *);
		if (!r) break;
		[rul appendSeq:[r instantiateRule]];
	}
	va_end(ap);
	return rul;
}

+ (id) optionalMany: (DBParserRule*)r1, ...
{
	va_list ap;
	DBParserRuleOptional *rul=[[[[self class]alloc]initWithAction:(SEL)0]autorelease];
	if (!rul) return nil;
	[rul appendSeq:[r1 instantiateRule]];
	va_start(ap, r1);
	for (;;) {
		DBParserRule *r;
		r=va_arg(ap, DBParserRule *);
		if (!r) break;
		[rul appendSeq:[r instantiateRule]];
	}
	va_end(ap);
	rul->many=YES;
	return rul;
}

- (void) invokeWithParser:(DBParser *)p
{
	BOOL matche1=NO;
	for (;;) {
		int i;
		BOOL nm=NO;
		for (i=0; i<_DBP_MAX_LA; i++) {
			if (tokens[i]==-1) break;
			int lai=[p _tlookAhead:i];
			if (tokens[i]!=lai) {
				nm=YES;
				break;
			}
		}
		if (nm) break;
		[self beginWithParser:p];
		[self matchedWithParser:p];
		matche1=YES;
		if (!many) break;
	}
}

- (void) preProcess
{
	[super preProcess];
}

- (NSString *) description
{
	return [NSString stringWithFormat:@"RULE optional"];
}

@end
